<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class news_cat extends CI_Controller 
{	protected $num_lang ;
	function __construct()
	{
		parent::__construct();
		
		//load helper
		$this->load->helper('login_helper');
		
			//load model

		$this->load->model('Mnews_cat');
		$this->load->model('Msetting');
		
		$this->num_lang = $this->Msetting->get_lang();


    //load libraries

    $this->load->library('pagination');

    $this->load->library('form_validation');
	// session
	 session_start();
		 if ( !isset($_SESSION['row_number']))

			$_SESSION['row_number']= 12;
	load_lang("admin");
	check_login();
	}

	function test()
	{
		$this->load->Model("Mpermission");
		$dat = $this->Mpermission->info_from_id(5);
		print_r($dat);
		$per = $dat[0]["per_module"];
		echo $per;
		$a =unserialize($per);
		load_module($a);
	}
	function index($page='')
	{
	
		$limit = $_SESSION['row_number'];

		$config['base_url'] = site_url().'/admin/news_cat/index/';

		$config['first_link'] = 'First';

		$config['last_link'] = 'Last';

		$config['next_link'] = '&gt;&gt;';

		$config['prev_link'] = '&lt;&lt;';

		$config['cur_tag_open'] = '<a href="#" class="current">';

		$config['cur_tag_close'] = '</a>';

		$config['uri_segment'] = 4;

		$config['num_links'] = 2;

		$config['total_rows'] = $this->Mnews_cat->count_all();

		$config['per_page'] = $limit;
		

		$this->pagination->initialize($config);

    if (empty($page))	$page = 0; //default value

    $data['result'] = $this->Mnews_cat->list_data($page,$limit);// $this->Muser->user_review($page, $limit);

    $data['title'] = 'Danh sách Ngành Hàng';

    $data['page'] = str_replace('&nbsp;', '', $this->pagination->create_links());

    $data['main'] = 'news_cat_review';

    $this->load->view('admin/layout/template_main', $data);
	
	}
	//upddate
	function update()
	{
		$id= $this->uri->segment(4);
			if ($this->input->post('update'))

    {
      //set rules

    $this->form_validation->set_rules('name_vi', 'Tên Loai sản phẩm(Tiếng Việt)', 'required');
	if($this->num_lang >1 )
      $this->form_validation->set_rules('name_en', 'Tên Loại sản phẩm(Tiếng Anh)', 'required');

  	$config['upload_path'] = './upload/news_cat/';
	  if(!is_dir($config['upload_path']) )
		{
			//echo 'as';
			@mkdir($path,777);
		}
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size'] = '800';
		$config['max_width'] = '800';
		$config['max_height'] = '500';
	
		$this->load->library('upload',$config);
 //     $this->form_validation->set_rules('avatar', 'avatar', 'callback_upload_file');
     
      $config['upload_path'] = './upload/news/';
	  if(!is_dir($config['upload_path']) )
		{
			//echo 'as';
			@mkdir($path,777);
		}
							
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size'] = '500';
		$config['max_width'] = '500';
		$config['max_height'] = '500';
	
		$this->load->library('upload',$config);
	//	$this->upload->initialize($config);
   
		if ($this->form_validation->run() == false )
		{	$data['missing'] = $this->form_validation->_error_array;}
    	  else
		{
			if(!empty($_FILES['img']['name']))
				{
					if(!$this->upload->do_upload("img"))
					{	
						$data['missing']['img']= $this->upload->display_errors();
							$data['result'] = $this->Mnews_cat->info_from_cat_id($id,'tbl_news_cat');
	
						//$data['news_cat'] = $this->Msub_news_cat->get_sub_news_cat();
						$data['main'] = 'news_cat_update';
					$data['num_lang'] = $this->num_lang;	
						$data['title'] = $this->lang->line('title_news_cat_create');
				
						$this->load->view('admin/layout/template_main', $data);
						
						return false;		
					//	$this->load->view('admin/template_main', $data);
					}
					
				}
		//	return false;

	  if ($this->form_validation->run() && $this->sub_update())

        redirect('admin/news_cat/', 'refresh');

      else
		{
        	$data['missing'] = $this->form_validation->_error_array;	
		}
			
		}
    
    }
    elseif ($this->input->post('close'))
		{
			redirect('admin/news_cat/', 'refresh');
		}
	$data['num_lang'] = $this->num_lang;	
	$data['main'] = 'news_cat_update';
	$data['result']= $this->Mnews_cat->info_form_id($id);
    $data['title'] = "Cập nhật Ngành Hàng";
	$this->load->view('admin/layout/template_main', $data);
	}
	function sub_update()
	{
		
		$id= $this->uri->segment(4);
		if(isset($_POST["update"]))
		{
			$status =$this->input->post('status');
			if($this->num_lang >1 )
			{
				if (!empty($_POST['img']))
				{
					$file = $this->Mnews_cat->info_from_cat_id($id,'tbl_news_cat');
					$path = "upload/news_cat/";
					$path = "upload/news_cat/".$file[0]['cat_img_index'];				
					@unlink($path);
					$hinh = $this->upload->data();
					$path = "./upload/news_cat/".$hinh['file_name'];
					$data = array (
									"cat_name" =>htmlentities($_POST["name_vi"],ENT_QUOTES,"UTF-8"),
									"cat_name_en" =>htmlentities($_POST["name_en"],ENT_QUOTES,"UTF-8"),
									"cat_status"=>$status ,'cat_img_index'=> $hinh['file_name'],	
									"cat_detail" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"),
									"cat_detail_en" => htmlentities($this->input->post("direction_en"),ENT_QUOTES,"UTF-8"),);	
					
				}	
				else
				{	
					$data = array (
									"cat_name" =>htmlentities($_POST["name_vi"],ENT_QUOTES,"UTF-8"),
									"cat_name_en" =>htmlentities($_POST["name_en"],ENT_QUOTES,"UTF-8"), 
									"cat_status"=>$status,
									"cat_detail" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"),
									"cat_detail_en" => htmlentities($this->input->post("direction_en"),ENT_QUOTES,"UTF-8"), 
								  );
				}
			}
			else
			{
				if (!empty($_POST['img']))
				{
					$file = $this->Mnews_cat->info_from_cat_id($id,'tbl_news_cat');
					$path = "upload/news_cat/";
					$path = "upload/news_cat/".$file[0]['cat_img_index'];				
					@unlink($path);	
					$hinh = $this->upload->data();
					$path = "./upload/news_cat/".$hinh['file_name'];
							$data = array ("cat_name" =>htmlentities($_POST["name_vi"],ENT_QUOTES,"UTF-8"),"cat_status"=>$status ,			"cat_detail" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"),'cat_img_index'=> $hinh['file_name'],);
						
				}	
				else
					$data = array ("cat_name" =>htmlentities($_POST["name_vi"],ENT_QUOTES,"UTF-8"), "cat_status"=>$status,"cat_detail" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"),);
			}
			if($this->num_lang > 1 )
			{	
				$this->Mnews_cat->update($data,$id,2) ;
				return true;
			}
			elseif ($this->num_lang == 1)
			{
				$this->Mnews_cat->update($data,$id,1);
				return true;
			}
			else
				return false;
		}
		else
			return false;
	}
		// proccess data for update	
	function create()
	{
	 if ($this->input->post('create'))
    {
      $this->form_validation->set_rules('name_vi', 'Tên Loai sản phẩm(Tiếng Việt)', 'required');
	if($this->num_lang >1 )
      $this->form_validation->set_rules('name_en', 'Tên Loại sản phẩm(Tiếng Anh)', 'required');
	  
	       
      $config['upload_path'] = './upload/news_cat/';
	  if(!is_dir($config['upload_path']) )
		{
			//echo 'as';
			@mkdir($path,777);
		}							
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size'] = '800';
		$config['max_width'] = '800';
		$config['max_height'] = '500';
	
		$this->load->library('upload',$config);
	//	$this->upload->initialize($config);
   
		if ($this->form_validation->run() == false )
		{	$data['missing'] = $this->form_validation->_error_array;}
    	  else
		{
		//	print_r();
			if(!empty($_FILES['img']['name']))
				{
					if(!$this->upload->do_upload("img"))
					{	
						$data['missing']['img']= $this->upload->display_errors();
						$data['main'] = 'news_cat_create';
						$data['num_lang'] = $this->num_lang;	
						$data['title'] = $this->lang->line('title_news_cat_create');
						$this->load->view('admin/layout/template_main', $data);
						return false;		
					//	$this->load->view('admin/template_main', $data);
					}
			
					
				}
		//	return false;

			 if ($this->form_validation->run() && $this->sub_create())
        redirect('admin/news_cat/', 'refresh');
      else
		{
        	$data['missing'] = $this->form_validation->_error_array;
		}
			
		}
    }

    elseif ($this->input->post('close'))

		{

			redirect('admin/news_cat/', 'refresh');

		}	
		 //reload template
	$data['num_lang'] = $this->num_lang;	
		$data['main'] = 'news_cat_create';

    $data['title'] = 'Thêm Dịch vụ';

		$this->load->view('admin/layout/template_main', $data);
	}
	function check_email()
	{
		$email=$this->uri->segment(4);
		if(!$this->Muser->check_email($email))
			echo "1";
		else
			echo "0";

	}
	
	function sub_create()
	{
		if(isset($_POST["create"]))
		{
/*		if($this->Muser->check_email(!$this->input->post("email")))
		{	
			$this->form_validation->_error_array["email"] = "This Email have been existed ."; 
		
			return false;
		
		} */
		$array = $this->Mnews_cat->get_last_id();
	//	print_r($array);
	
		if(empty($array) || $array['cat_id'] == 0 ) 
				$id = 1;
		else
			$id = $array['cat_id']+1;			
		$status = $this->input->post('cat_status');
		if($this->num_lang > 1)	
		{
		if (!empty ($_FILES['img']['name']))
		{
			$hinh = $this->upload->data();
			$path = "./upload/news_cat/".$hinh['file_name'];
			$data = array ("cat_id"=>$id,"cat_status"=>$status,"cat_img_index"=>$hinh["file_name"],"cat_lang"=>"2","cat_name_en" =>htmlentities($_POST["name_en"],ENT_QUOTES,"UTF-8"),'cat_status'=>$this->input->post('status'),"cat_name" =>htmlentities($_POST["name_vi"],ENT_QUOTES,"UTF-8"),"cat_detail_en" => htmlentities($this->input->post("direction_en"),ENT_QUOTES,"UTF-8"),
				"cat_detail" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"), );
		
		}
		else
			{
				$data = array ("cat_id"=>$id,"cat_status"=>$status,"cat_lang"=>"2","cat_name_en" =>htmlentities($_POST["name_en"],ENT_QUOTES,"UTF-8"),'cat_status'=>$this->input->post('status'),"cat_name" =>htmlentities($_POST["name_vi"],ENT_QUOTES,"UTF-8"),"cat_detail_en" => htmlentities($this->input->post("direction_en"),ENT_QUOTES,"UTF-8"),
				"cat_detail" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"), );
			}
		}
		else
		{
			if (!empty ($_FILES['img']['name']))
			{ 
			$hinh = $this->upload->data();
			$path = "./upload/news_cat/".$hinh['file_name'];
			
			$data = array ( "cat_id"=>$id , "cat_status"=>$status, "cat_lang"=>"1","cat_img_index"=>$hinh["file_name"], "cat_name" =>htmlentities($_POST["name_vi"],ENT_QUOTES,"UTF-8"),'cat_status'=>$this->input->post('status'),"cat_detail" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"), );
			
			}
			else
			{
				$data = array ( "cat_id"=>$id , "cat_status"=>$status, "cat_lang"=>"1", "cat_name" =>htmlentities($_POST["name_vi"],ENT_QUOTES,"UTF-8"),'cat_status'=>$this->input->post('status'),"cat_detail" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"), );
			}
		}
		if($this->num_lang > 1 or $this->num_lang == 1)
		{	$this->Mnews_cat->insert($data);
			return true;
		}
		else
			return false;
		}
		else
			return false;
	}
	
	 function upload_file()
  {
    $input_file = 'img';
    if ($_FILES[$input_file]['error'] == 0  )
    {	
      $path_directory = './upload/news_cat/';
      if ( ! is_dir($path_directory)) mkdir($path_directory);
      $config['upload_path'] = $path_directory;
      $config['allowed_types'] = 'gif|jpg|png';
      $config['max_size'] = '500'; //500kB
      $this->load->library('upload', $config);
      if ($this->upload->do_upload($input_file))
      {
		 
        $info_file = $this->upload->data();
		
        $file_path = $info_file['file_name'];
     	$_POST['img'] = $file_path;
      }
      else
      {
		//$data["error"]= $this->upload->display_errors();//$data["missing"] = array("img"=>$this->upload->display_errors());
        return false;
      }
    }
    return true;
  }
	function request()
	{
		//determine 'action'
		$require = array('show', 'delete');

		foreach ($_POST as $key=>$value)

		{

			if (in_array($key, $require))

			{

				$act = $key;
				
			}

		}



		//process 'action'

		if (! empty($act))

		{

			switch ($act)

			{

				case 'show': //show

				{
				
					$_SESSION['row_number'] = $this->input->post('row_number');
					
				} break;



				case 'delete': //delete

				{

					$this->Mnews_cat->delete();

				} break;

			}//end switch



			redirect('admin/news_cat/', 'refresh');

		}//end if

	}
	public function delete($id)
	{
		if($id >0 )
			{
				$file = $this->Mnews_cat->info_from_cat_id($id,'tbl_news_cat');
			if (!empty($file[0]['cat_img_index']))
			{
				$path = "upload/news_cat/";
				$path = "upload/news_cat/".$file[0]['cat_img_index'];				
				@unlink($path);
			}
			$this->Mnews_cat->del_item($id);	
			}
		redirect('admin/news_cat/', 'refresh');
		
	}
		public function del_image($id)
 	{
			$file = $this->Mnews->info_from_id($id,'tbl_news');
				
			$path = "./upload/news_cat/".$file[0]['prod_image'];
			if(!file_exists($path))
					@unlink($path);
			if($this->Mnews_cat->del_img($id))
				echo "<script charset='UTF-8' > alert('Xoa hinh thanh cong !'); document.location.href='".base_url()."index.php/admin/news_cat/update/$id' </script>";	
			else
				echo "<script charset='UTF-8' > alert('co loi trong qua trinh xoa ... hay thu lai lan nua !'); document.location.href='".base_url()."index.php/admin/news_cat/update/$id' </script>";					
	}
	
}
?>
